﻿using FinalPointSet.ViewModel.Page.MockData;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Controls;

namespace FinalPointSet.View.Page.MockData
{
    /// <summary>
    /// GeneratePage.xaml 的交互逻辑
    /// </summary>
    public partial class GeneratePage : System.Windows.Controls.Page
    {
        public GeneratePage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// datagrid行加载事件,下面的逻辑是为了动态添加表头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            //检验传入的参数
            if (sender is not DataGrid dataGrid) return;
            if (e.Row.Item is not List<string> rowData) return;
            if (dataGrid.Columns.Count >= rowData.Count) return; //若添加的表头个数已经够了, 则直接退出

            //提取表头
            GeneratePageViewModel? viewModel = null;
            if (DataContext != null)
                viewModel = (GeneratePageViewModel)DataContext;

            List<string> header = [];
            if (viewModel != null)
                header = viewModel.Header;

            //动态加载datagrid的数据
            //检查当前DataGrid的列数是否足够
            for (int i = 0; i < rowData.Count; i++)
            {
                string head;
                if (header != null && header.Count > 0)
                {
                    head = header[i];
                }
                else
                {
                    head = $"Column {dataGrid.Columns.Count + 1}";
                }
                //动态创建新列  
                var newColumn = new DataGridTextColumn
                {
                    Header = head,
                    Binding = new System.Windows.Data.Binding(string.Format("[{0}]", dataGrid.Columns.Count))
                };

                //将新列添加到DataGrid中  
                dataGrid.Columns.Add(newColumn);
            }
        }

        private void Page_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            Debug.Print("GeneratePage.Page_Unloaded(), 清空预览生成结果Datagrid的表头");
            PreviewDataGrid?.Columns.Clear();
        }
    }
}
